package com.cskaoyan.batch;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 * 创建日期: 2022/04/21 17:12
 *
 * @author ciggar
 */
public class BatchDemo {

    static Connection connection;

    static {

        connection = JDBCUtils.getConnection();
    }


    public static void main(String[] args) {

        long t1 = System.currentTimeMillis();

        insertUseForeach();

        long t2 = System.currentTimeMillis();

        insertUseStatement();

        long t3 = System.currentTimeMillis();

        insertUsePreparedStatement();

        long t4 = System.currentTimeMillis();

        System.out.println("for循环插入的时间：" + (t2-t1) + "毫秒");             // 1202ms
        System.out.println("statement批处理：" + (t3-t2) + "毫秒");               // 1010ms
        System.out.println("PreparedStatement批处理：" + (t4-t3) + "毫秒");       // 917ms


    }


    // 向cskaoyan表中插入1000条数据

    // for循环一条一条的插入
    public static void insertUseForeach(){

        try {

            Statement statement = connection.createStatement();
            for (int i = 0; i < 100000; i++) {
                statement.executeUpdate("insert into cskaoyan values (null,'foreach',100,'cskaoyan')");
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    // statement的批处理
    public static void insertUseStatement(){

        try {
            Statement statement = connection.createStatement();

            for (int i = 0; i < 100000; i++) {
                String sql = "insert into cskaoyan values (null,'statement',200,'statement')";
                // 往批处理里面添加SQL语句
                statement.addBatch(sql);
            }
            // 批量的执行SQL语句
            statement.executeBatch();

        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    // preparedStatement 的批处理
    public static void insertUsePreparedStatement(){

        try {
            PreparedStatement preparedStatement = connection.prepareStatement("insert into cskaoyan values (null,?,?,?)");

            for (int i = 0; i < 100000; i++) {
                preparedStatement.setString(1, "preparedStatement");
                preparedStatement.setInt(2, 300);
                preparedStatement.setString(3, "preparedStatement");
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();

        }catch (Exception ex) {
            ex.printStackTrace();
        }


    }




}
